package com.fita.webpay.processor.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.entity.pay.PayConfig;
import com.fita.webpay.entity.PaymentContext;
import com.fita.webpay.entity.config.AlipayConfig;
import com.fita.webpay.entity.prepare.PrepareResponse;
import com.fita.webpay.processor.PaymentProcessor;

@Component("alipayProcessor")
public class AlipayProcessor implements PaymentProcessor {

    private static final Logger logger = LoggerFactory.getLogger(WechatpayProcessor.class);
    
    private AlipayConfig alipayConfig;
    
    @Autowired
    public void initConfig(@Value("#{payment['alipay.appId']}") String appid,
                           @Value("#{payment['alipay.key']}") String key,
                           @Value("#{payment['alipay.public.key']}") String publicKey,
                           @Value("#{payment['alipay.notifyUrl']}") String notifyUrl){
        
        this.alipayConfig = new AlipayConfig(appid, key, publicKey, notifyUrl);
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.webpay.processor.PaymentProcessor#prepare(com.fita.webpay.entity.PaymentContext)
     */
    public PrepareResponse prepare(PaymentContext paymentContext) {
        
        logger.info("get config [{}]", System.getProperty("yop.sdk.config.file"));
        PrepareResponse prepareResponse = new PrepareResponse();
        
        try {
            
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                                                                alipayConfig.getAppid(),
                                                                alipayConfig.getPrivateKey(), 
                                                                "json", "UTF-8", 
                                                                alipayConfig.getPublicKey(),
                                                                "RSA2");
            
            AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
            
            AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
            model.setOutTradeNo(paymentContext.getOutTradeNo());
            model.setSubject(paymentContext.getSubject());
            model.setTotalAmount(paymentContext.getAmountAsYuan());
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(alipayConfig.getNotifyUrl());
            // 设置同步地址
            alipay_request.setReturnUrl(paymentContext.getCallbackUrl());   
            
            // form表单生产
            String form = "";
            
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipay_request).getBody();
            
            prepareResponse.success().data("alipayform", form);
                
        } catch (AlipayApiException e) {
            logger.error("get error ", e);
            prepareResponse.fail().message("请求支付宝失败!");
        } catch (Exception e) {
            logger.error("get error ", e);
            prepareResponse.fail().message("创建支付宝支付环境失败!");
            
        }
        
        logger.info("prepare success with result [{}]", JsonUtils.toJson(prepareResponse));
        
        return prepareResponse;
        
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.webpay.processor.PaymentProcessor#validate(com.demo2do.core.wechat.entity.pay.PayConfig)
     */
    public boolean validate(PayConfig payConfig) {
        // 此方法在此无用
        return false;
    }

}
